package com.md.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.md.model.page.PageResponse;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 2021-10-20 22:10
 *
 * @author 刘骄阳
 */
@UtilityClass
public class PageUtil {

  /**
   * 将IPage转为PageResponse
   *
   * @param page page
   * @param <T>  枚举
   * @return PageResponse
   */
  public static <T> PageResponse<T> buildPageResponse(final IPage<T> page) {
    return PageResponse.of(page.getPages(), page.getTotal(), page.getCurrent(), page.getSize(), page.getRecords());
  }

  public static <T> PageResponse<T> buildPageResponse(final List<T> list,
                                                      final Long total,
                                                      final Long pageNum,
                                                      final Long pageSize) {
    long pages = (total + pageSize - 1) / pageSize;

    return PageResponse.of(pages, total, pageNum, pageSize, list);
  }

  public static <T> List<T> limitList(final List<T> list, final Long pageNum, final Long pageSize) {
    if (ObjectUtil.isEmpty(list)) {
      return Lists.newArrayList();
    }
    // 计算分页的起始位置和结束位置
    long startIndex = (pageNum - 1) * pageSize;
    long endIndex = Math.min(startIndex + pageSize, list.size());

    // 如果 startIndex 超出数据范围，返回空列表
    if (startIndex >= list.size()) {
      return Lists.newArrayList();
    }

    // 返回分页后的数据
    return list.subList((int) startIndex, (int) endIndex);
  }

  public static <T, U> PageResponse<U> buildPageResponse(final IPage<T> page, final Function<T, U> apply) {
    return PageResponse.of(page.getPages(), page.getTotal(), page.getCurrent(), page.getSize(),
      page.getRecords().stream().map(apply).collect(Collectors.toList()));
  }
}
